package cjyyp.nio网络编程;

import cjyyp.buffer.util.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class 单线程阻塞式服务端 {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        List<SocketChannel> socketChannelList = new ArrayList<>();
        while (true) {
            log.info("连接之前。。。");
            SocketChannel socketChannel = serverSocketChannel.accept();//此方法默认为阻塞，等待客户端连接
            log.info("连接之后。。。");
            socketChannelList.add(socketChannel);
            socketChannelList.forEach(
                    channel -> {
                        try {
                            log.info("接收数据之前。。。");
                            channel.read(byteBuffer);//此方法默认阻塞，等待客户端发送数据
                            log.info("接收数据之后。。。");
                            byteBuffer.flip();
                            ByteBufferUtil.debugAll(byteBuffer);
                            byteBuffer.clear();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        }


    }
}
